package com.ruoyi.web.utils;

import org.springframework.data.redis.util.ByteUtils;
import org.tron.trident.core.transaction.SignatureValidator;
import org.tron.trident.utils.Numeric;
import org.web3j.crypto.Hash;

public class TronVerifyMessage {

	public static final String TRX_MESSAGE_HEADER = "\u0019TRON Signed Message:\n32";

	public static boolean verify(String message, String signature, String address){

		byte[] trxMessageHeaderBytes = TRX_MESSAGE_HEADER.getBytes();

		String messageReplace = Numeric.toHexString(message.getBytes()).replace("0x", "");

		String sha3Replace = Hash.sha3(messageReplace).replace("0x", "");

		byte[] hexStringToByteArray = Numeric.hexStringToByteArray(sha3Replace);

		byte[] concat = ByteUtils.concat(trxMessageHeaderBytes, hexStringToByteArray);

		byte[] sha3Concat = Hash.sha3(concat);

		String sha3ConcatReplace = Numeric.toHexString(sha3Concat).replace("0x", "");

		String signatureReplace = signature.replace("0x", "");

		String substring = signatureReplace.substring(128, 130);

		if ("1b".equals(substring)){
			signatureReplace = signatureReplace.substring(0, 128) + "00";
		} else {
			signatureReplace = signatureReplace.substring(0, 128) + "01";
		}

		boolean verify = SignatureValidator.verify(sha3ConcatReplace, signatureReplace, address);

		return verify;
	}
}
